#include "parser.h" 

Parser::Parser(const char * filename, Processor * p) {
  sourcefile.open(filename);
  //p = processor;
  string line;
  int count = 1;
  unsigned long itemp = 0;
  while(getline(sourcefile, line)) {
    bool ret = parse(line.c_str());
    if(ret) {
      boost::shared_ptr<Command> c(new Command(pIns, pDst, pSrc));
      p->addCommand(c);
      //cout << "adding: " << pIns << " " << pDst << " " << pSrc << endl;
      //if(pIns == "ldi") {
        //itemp = atoi(pSrc.c_str());
        //if(itemp > 255) {
          //cout << "8bit dude!" << endl;
          //break;
        //}
        //else
          //p.setRegister(pDst,itemp);
      //}
      //else if(pIns == "prt") {
        //cout << p.getRegister(pDst).to_ulong() << endl;
      //}
      //else if(pIns == "add") { 
        //p.push(
            //p.getRegister(pDst).to_ulong() + p.getRegister(pSrc).to_ulong()
            //);
      //}
      //else if(pIns == "push") {
        //itemp = atoi(pDst.c_str());
        //if(itemp > 255) {
          //cout << "8bit dude!" << endl;
          //break;
        //}
        //else
          //p.push(itemp);
      //}
      //else if(pIns == "pop") {
        //p.setRegister(pDst, p.pop());
      //}
      //else {
        //cout << pIns << " is unknown" << endl;
        //break;
      //}
      //cout << "line " << count << " ok!" << endl;
    }
    else {
      cout << "line " << count << " is invalid!" << endl;
      break;
    }
    
    count++;
  }
}

Parser::~Parser() {

}

bool Parser::parse(const char * line) {
  dst = +(anychar_p - space_p - ch_p(','));
  src = +(alnum_p - space_p - ch_p(','));
  val = +(xdigit_p - space_p - ch_p(','));
  instruction = +(anychar_p - space_p - ch_p(',') - ch_p(';'));
  comment = +(ch_p(';') >> *anychar_p >> *space_p);
  expression =
    *space_p >> *comment >> *space_p >> *(
    instruction[assign_a(pIns)]
    >> space_p
    >> dst[assign_a(pDst)]
    >> *ch_p(',')
    >> *src[assign_a(pSrc)]
    >> *space_p) >> *comment >> *space_p;

  pI = spirit::parse(line, expression);
  return pI.full;
}
